<template>
  <div>
    <el-container>
      <el-header style="height:auto;">
        <el-date-picker
          v-model="timerange"
          type="datetimerange"
          value-format="timestamp"
          :picker-options="pickerOptions"
          range-separator="至"
          :default-time="['0:00:00', '23:59:59']"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
        <el-input
          v-model="kwInput"
          placeholder="输入关键词搜索"
          style="width: 20%"
          clearable
          class=""
          @keyup.native.enter="handleSearch"
        >
          <el-button slot="append" style="width: 180px" type="success" icon="el-icon-search" @click="handleSearch">搜索
          </el-button>
        </el-input>
        <el-button type="success" @click="handleAction('create')">新增</el-button>
      </el-header>
      <el-main>
        <el-table
          ref="table"
          v-loading="listLoading"
          :data="data.filter(item => !kwInput || item.name.toLowerCase().includes(kwInput.toLowerCase()) ||item.id_product.toLowerCase().includes(kwInput.toLowerCase()))"
          border
          height="750"
          :default-sort="{prop: 'impression', order: 'descending'}"
          @sort-change="handleSort"
        >
          <el-table-column type="expand">
            <template slot-scope="props">
              <el-form label-position="left" style="margin-bottom: 0px">
                <el-form-item label="商品名称">
                  <span>{{ props.row.name }}</span>
                </el-form-item>
                <el-form-item label="所属region">
                  <span>{{ props.row.region }}</span>
                </el-form-item>
                <el-form-item label="开始时间">
                  <span>{{ props.row.create_at }}</span>
                </el-form-item>
              </el-form>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="main_image" label="产品" width="100">
            <template slot-scope="scope">
              <a :href="scope.row.link" target="_blank"><img :src="scope.row.image" width="56"></a><br>
            </template>
          </el-table-column>
          <el-table-column align="center" label="shop" prop="id_shop" />
          <el-table-column align="center" label="id product" prop="id_product">
            <template slot-scope="scope">
              <a :href="scope.row.link" target="_blank">{{ scope.row.id_product }}</a><br>
            </template>
          </el-table-column>
          <el-table-column align="center" label="历史销售" prop="historical_sold" sortable="custom">
            <template slot-scope="scope">
              <span @click="handleShowHistory(scope.row)">{{ scope.row.historical_sold }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="sold" prop="sold" sortable="custom">
            <template slot-scope="scope">
              <span @click="handleShowHistory(scope.row)">{{ scope.row.sold }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="cmt_count" prop="cmt_count" sortable="custom" />
          <el-table-column align="center" label="view_count" prop="view_count" sortable="custom" />
          <el-table-column align="center" label="liked_count" prop="liked_count" sortable="custom" />
          <el-table-column align="center" label="shop_location" prop="shop_location" sortable="custom" />
          <el-table-column align="center" prop="price" sortable="custom" label="price">
            <template slot-scope="scope">
              <span @click="handleAdsStatics(scope.row)">{{ scope.row.price }}{{ scope.row.currency }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="item_create" sortable="custom" label="item_create" />
          <el-table-column align="center" label="操作" width="280">
            <template slot-scope="scope">
              <el-button size="mini" type="success" @click="handleAction('edit', scope.row)">修改</el-button>
              <el-button size="mini" type="danger" @click="handleAction('delete', scope.row)">删除</el-button>
            </template>
          </el-table-column>

        </el-table>

        <el-pagination
          v-if="data.length"
          background
          class="mt-pagination"
          :current-page="page"
          :page-sizes="[10,20,50,100,200,500]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </el-main>
    </el-container>
    <el-dialog
      :title="title"
      :visible.sync="innerDialogVisible"
      width="60%"
    >
      <el-form ref="form" :model="form" label-width="160px">
        <el-form-item v-if="action !== 'delete'" label="解析链接">
          <el-input v-model="orginal_link" placeholder="请输入内容" class="input-with-select">
            <el-button slot="append" icon="el-icon-search" @click="handleOriginalLink" />
          </el-input>
        </el-form-item>
        <el-form-item label="region">
          <el-select v-model="form.region" tyle="width: 100%" filterable clearable placeholder="选择账号区域">
            <el-option
              v-for="item in regions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="action !== 'delete'" label="id_product">
          <el-input v-model="form.id_product" />
        </el-form-item>
        <el-form-item v-if="action !== 'delete'" label="id_shop">
          <el-input v-model="form.id_shop" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="innerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirm">保存</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :title="historyTitle"
      :visible.sync="historyDialogVisible"
      width="60%"
    >
      <el-table
        :data="history_data"
        border
        :default-sort="{prop: 'timestamp', order: 'descending'}"
      >
        <el-table-column align="center" prop="timestamp" label="时间" width="100" />
        <el-table-column align="center" label="historical_sold" prop="historical_sold" />
        <el-table-column align="center" label="sold" prop="sold" sortable="custom" />
        <el-table-column align="center" label="cmt_count" prop="cmt_count" sortable="custom" />
        <el-table-column align="center" label="view_count" prop="view_count" sortable="custom" />
        <el-table-column align="center" label="liked_count" prop="liked_count" sortable="custom" />
        <el-table-column align="center" label="price_min" prop="price_min" sortable="custom" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="historyDialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Get, Post, Put, Delete } from '@/api/shopee/shopeeproductmonitor'
import qs from 'qs'

const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}

export default {
  data() {
    return {
      action: '',
      listLoading: false,
      kwInput: '',
      order_by: 'sold',
      order_desc: 1,
      // pagination
      pagesize: 50,
      page: 1,
      total: 0,
      timerange: '',
      regions: [{
        label: '新加坡站点',
        value: 'SG'
      },
      {
        label: '马来西亚站点',
        value: 'MY'
      }
      ],
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime())
            start.setHours(0, 0, 0)
            picker.$emit('pick', [start, end])
          }
        },
        {
          text: '昨天',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 1)
            start.setHours(0, 0, 0)
            end.setTime(end.getTime() - 3600 * 1000 * 24 * 1)
            end.setHours(23, 59, 59)
            picker.$emit('pick', [start, end])
          }
        },
        {
          text: '最近3天',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 3)
            start.setHours(0, 0, 0)
            picker.$emit('pick', [start, end])
          }
        },
        {
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            start.setHours(0, 0, 0)
            end.setTime(end.getTime() - 3600 * 1000 * 24)
            end.setHours(23, 59, 59)
            picker.$emit('pick', [start, end])
          }
        },
        {
          text: '过去14天',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 14)
            start.setHours(0, 0, 0)
            end.setTime(end.getTime() - 3600 * 1000 * 24)
            end.setHours(23, 59, 59)
            picker.$emit('pick', [start, end])
          }
        },
        {
          text: '过去30天',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            start.setHours(0, 0, 0)
            end.setTime(end.getTime() - 3600 * 1000 * 24)
            end.setHours(23, 59, 59)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            start.setHours(0, 0, 0)
            end.setHours(23, 59, 59)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近6个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 180)
            start.setHours(0, 0, 0)
            end.setHours(23, 59, 59)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近1年',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 365)
            start.setHours(0, 0, 0)
            end.setHours(23, 59, 59)
            picker.$emit('pick', [start, end])
          }
        }
        ]
      },
      data: [],
      orginal_link: '',
      form: {
        id: '',
        region: '',
        id_product: '',
        id_shop: ''
      },
      innerDialogVisible: false,
      title: '添加广告产品',
      historyTitle: '历史销售记录',
      historyDialogVisible: false,
      history_data: []
    }
  },
  created() {
    this.getList()
  },
  methods: {
    handleShowHistory(row) {
      this.history_data = row.sold_history
      this.historyTitle = row.id_product + '产品销售历史数据'
      this.historyDialogVisible = true
    },
    handleOriginalLink() {
      if (this.orginal_link.length === 0) {
        return
      }
      const b = this.orginal_link.split('.')
      this.form.id_product = b[b.length - 1]
      this.form.id_shop = b[b.length - 2]
      this.form.region = b[0].replace('https://', '')
    },
    resetTemp() {
      this.form = {
        id: '',
        region: '',
        id_product: '',
        id_shop: ''
      }
    },
    onSubmit() {
      Post(this.form).then((response) => {
        this.form.id = ''
        this.innerDialogVisible = false
        this.getList()
      }).catch(error => {
        console.log(error)
      })
    },
    getList() {
      this.listLoading = true
      this.time_start = this.timerange ? this.timerange[0] : ''
      this.time_end = this.timerange ? this.timerange[1] : ''
      Get(null,
        qs.stringify({
          kw: this.kwInput,
          start: this.timerange ? this.timerange[0] : '',
          end: this.timerange ? this.timerange[1] : '',
          pagesize: this.pagesize,
          page: this.page,
          order_by: this.order_by,
          order_desc: this.order_desc
        })).then((response) => {
        this.data = response.data.data
        this.total = response.data.total
        this.listLoading = false
        this.$nextTick(() => {
          this.$refs['table'].doLayout()
        })
      }).catch(error => {
        console.log(error)
        this.listLoading = false
      })
    },
    handleAction(action, row) {
      this.action = action
      switch (action) {
        case 'create':
          this.width = '50%'
          this.title = '增加新广告产品'
          this.resetTemp()
          this.innerDialogVisible = true
          break
        case 'delete':
          this.width = '30%'
          this.title = `确认要删除 ${row.id_product}?`
          this.form = Object.assign({}, row)
          this.innerDialogVisible = true
          break
        case 'edit':
          this.width = '50%'
          this.title = `修改广告产品 ${row.id_product}`
          this.form = Object.assign({}, row)
          console.log(this.form, row)
          this.innerDialogVisible = true
          break
      }
    },
    confirm() {
      const _data = this.form
      switch (this.action) {
        case 'create':
          Post(this.form
          ).then(response => {
            this.innerDialogVisible = false
            this.getList()
          })
          break
        case
          'delete'
          :
          Delete(_data.id).then((response) => {
            this.innerDialogVisible = false
            this.getList()
          })
          break
        case
          'edit'
          :
          Put(_data.id, _data).then((response) => {
            this.innerDialogVisible = false
            this.$emit('reload')
            this.getList()
            this.notify('更新成功')
          })
          break
      }
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    },
    handleSearch() {
      this.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    }
  }

}
</script>

<style scoped>
table, tr {
  border-color: black;
}

.el-header {
  height: 120px;
  margin-top: 10px;
}

.el-header, .el-footer {
  color: white;
}

.demo-table-expand.el-form-item {
  margin-bottom: 0px;
}
</style>
